using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using LiteTools.service;
using Sunny.UI;

namespace LiteTools.forms
{
    public partial class ConfigDataServiceForm : UIForm
    {
        private Dictionary<string, string> DataBaseStr = new Dictionary<string, string>
        {
            { DataKeys.Server, string.Empty },
            { DataKeys.Port, string.Empty },
            { DataKeys.Database, string.Empty },
            { DataKeys.Uid, string.Empty },
            { DataKeys.Pwd, string.Empty },
            { DataKeys.Charset, string.Empty }
        };

        private int counter = 0;

        private class DataKeys
        {
            public const string Server = "Server";
            public const string Port = "Port";
            public const string Database = "Database";
            public const string Uid = "Uid";
            public const string Pwd = "Pwd";
            public const string Charset = "Charset";

            public static readonly string[] Charsets = { "utf8", "gbk", "big5", "latin1", "cp1251", "koi8r" };
        }

        public ConfigDataServiceForm()
        {
            InitializeComponent();
            charset_type.SelectedIndex = 0;
            InitFullDataBaseContent();
            password.PasswordChar = '*';
            ReadExistConfig();
        }

        private void ReadExistConfig()
        {
            var combine = Path.Combine(Environment.CurrentDirectory, "db_connection.txt");
            if (!File.Exists(combine))
            {
                using (var writer = File.CreateText(combine))
                {
                    writer.Write(string.Empty);
                    writer.Close();
                }
            }

            var fullContent = File.ReadAllText(combine);
            try
            {
                var valid = new Regex(
                    "Server=([0-9a-zA-Z]+\\.){2,3}([0-9a-zA-Z]+);Port=\\d{1,5};Database=.+;Uid=.+;Pwd=.+;Charset=(utf8|gbk|big5|latin1|cp1251|koi8r)");
                if (valid.IsMatch(fullContent))
                {
                    var properties = fullContent.Split(";");
                    foreach (var property in properties)
                    {
                        if (!property.Contains("="))
                        {
                            continue;
                        }

                        var strings = property.Split("=");
                        DataBaseStr.Remove(strings[0]);
                        DataBaseStr.Add(strings[0], strings[1]);
                    }

                    FillEachContent();
                    full_database_content.Text = GetFullDataStr(true);
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }

        private void InitFullDataBaseContent()
        {
            DataBaseStr = null;
            DataBaseStr = new Dictionary<string, string>
            {
                { DataKeys.Server, string.Empty },
                { DataKeys.Port, string.Empty },
                { DataKeys.Database, string.Empty },
                { DataKeys.Uid, string.Empty },
                { DataKeys.Pwd, string.Empty },
                { DataKeys.Charset, string.Empty }
            };
            DataBaseStr.Remove(DataKeys.Charset);
            DataBaseStr.Add(DataKeys.Charset, DataKeys.Charsets[charset_type.SelectedIndex]);
            full_database_content.Text = GetFullDataStr(true);
        }

        private void close_form_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void confirm_form_Click(object sender, EventArgs e)
        {
            // 衔接查数据库信息是否完整，不完整不允许填入
            if (DataBaseStr.ContainsValue(string.Empty))
            {
                UIMessageTip.ShowError(confirm_form, "数据库连接信息不完整，请补全信息再操作！", 1000, true);
                return;
            }

            var combine = Path.Combine(Environment.CurrentDirectory, "db_connection.txt");
            if (!File.Exists(combine))
            {
                using (var writer = File.CreateText(combine))
                {
                    writer.Write(GetFullDataStr(false));
                    writer.Close();
                }
            }

            var mySqlConnection = DbService.GetConnection(GetFullDataStr(false));
            if (mySqlConnection == null)
            {
                UIMessageTip.ShowError(confirm_form, "您设置的数据库连接不通，请确认参数！", 1500, true);
                return;
            }

            mySqlConnection.Close();
            File.WriteAllText(combine, GetFullDataStr(false));
            UIMessageTip.ShowOk("更新数据库信息成功！");
            Close();
        }

        private void url_Leave(object sender, EventArgs e)
        {
            var isIp = new Regex("([0-9a-zA-Z]+\\.){2,3}([0-9a-zA-Z]+)");
            if (!isIp.IsMatch(url.Text))
            {
                UIMessageTip.ShowError(url, "请填写正确的ip地址！", 1000, true);
                url.Text = string.Empty;
                return;
            }

            DataBaseStr.Remove(DataKeys.Server);
            DataBaseStr.Add(DataKeys.Server, url.Text);
            // 数据正确就刷新完整信息
            full_database_content.Text = GetFullDataStr(true);
        }

        private string GetFullDataStr(bool hidePwd)
        {
            var builder = new StringBuilder();
            builder.Append(DataKeys.Server).Append("=").Append(DataBaseStr[DataKeys.Server]).Append(";");
            builder.Append(DataKeys.Port).Append("=").Append(DataBaseStr[DataKeys.Port]).Append(";");
            builder.Append(DataKeys.Database).Append("=").Append(DataBaseStr[DataKeys.Database]).Append(";");
            builder.Append(DataKeys.Uid).Append("=").Append(DataBaseStr[DataKeys.Uid]).Append(";");
            if (!string.IsNullOrEmpty(DataBaseStr[DataKeys.Pwd]))
            {
                if (hidePwd)
                {
                    builder.Append(DataKeys.Pwd).Append("=").Append("**********").Append(";");
                }
                else
                {
                    builder.Append(DataKeys.Pwd).Append("=").Append(DataBaseStr[DataKeys.Pwd]).Append(";");
                }
            }
            else
            {
                builder.Append(DataKeys.Pwd).Append("=").Append(string.Empty).Append(";");
            }

            builder.Append(DataKeys.Charset).Append("=").Append(DataBaseStr[DataKeys.Charset]).Append(";");
            return builder.ToString();
        }

        private void FillEachContent()
        {
            url.Text = DataBaseStr[DataKeys.Server] != string.Empty ? DataBaseStr[DataKeys.Server] : string.Empty;
            port.Text = DataBaseStr[DataKeys.Port] != string.Empty ? DataBaseStr[DataKeys.Port] : string.Empty;
            data_base.Text = DataBaseStr[DataKeys.Database] != string.Empty
                ? DataBaseStr[DataKeys.Database]
                : string.Empty;
            user_name.Text = DataBaseStr[DataKeys.Uid] != string.Empty ? DataBaseStr[DataKeys.Uid] : string.Empty;
            password.Text = DataBaseStr[DataKeys.Pwd] != string.Empty ? DataBaseStr[DataKeys.Pwd] : string.Empty;
            switch (DataBaseStr[DataKeys.Charset])
            {
                case "utf8":
                    charset_type.SelectedIndex = 0;
                    return;
                case "gbk":
                    charset_type.SelectedIndex = 1;
                    return;
                case "big5":
                    charset_type.SelectedIndex = 2;
                    return;
                case "latin1":
                    charset_type.SelectedIndex = 3;
                    return;
                case "cp1251":
                    charset_type.SelectedIndex = 4;
                    return;
                case "koi8r":
                    charset_type.SelectedIndex = 5;
                    return;
                default:
                    charset_type.SelectedIndex = 0;
                    return;
            }
        }

        private void full_database_content_Leave(object sender, EventArgs e)
        {
            if (counter == 0)
            {
                counter++;
                return;
            }

            counter++;
            var valid = new Regex(
                "Server=([0-9a-zA-Z]+\\.){2,3}([0-9a-zA-Z]+);Port=\\d{1,5};Database=.+;Uid=.+;Pwd=.+;Charset=(utf8|gbk|big5|latin1|cp1251|koi8r)");
            // 不能通过校验的话就全部都重置
            if (!valid.IsMatch(full_database_content.Text))
            {
                UIMessageTip.ShowError(full_database_content, "连接信息错误！", 1000, true);
                if (full_database_content.Text != string.Empty) return;
                ClearAndReset();
                return;
            }

            var properties = full_database_content.Text.Split(";");
            foreach (var property in properties)
            {
                var strings = property.Split("=");
                DataBaseStr.Remove(strings[0]);
                DataBaseStr.Add(strings[0], strings[1]);
            }

            FillEachContent();
        }

        private void ClearAndReset()
        {
            url.Text = string.Empty;
            user_name.Text = string.Empty;
            password.Text = string.Empty;
            port.Text = string.Empty;
            password.Text = string.Empty;
            data_base.Text = string.Empty;
            charset_type.SelectedIndex = 0;
            InitFullDataBaseContent();
            counter = 0;
        }

        private void port_Leave(object sender, EventArgs e)
        {
            var regex = new Regex("\\d{1,5}");
            if (!regex.IsMatch(port.Text))
            {
                UIMessageTip.ShowError(port, "端口号错误，请设置正确的端口信息！", 1000, true);
                port.Text = string.Empty;
                return;
            }

            DataBaseStr.Remove(DataKeys.Port);
            DataBaseStr.Add(DataKeys.Port, port.Text);
            full_database_content.Text = GetFullDataStr(true);
        }

        private void data_base_Leave(object sender, EventArgs e)
        {
            if (data_base.Text == string.Empty)
            {
                UIMessageTip.ShowError(data_base, "请设置正确的数据库名称！", 1000, true);
                return;
            }

            DataBaseStr.Remove(DataKeys.Database);
            DataBaseStr.Add(DataKeys.Database, data_base.Text);
            full_database_content.Text = GetFullDataStr(true);
        }

        private void user_name_Leave(object sender, EventArgs e)
        {
            if (user_name.Text == string.Empty)
            {
                UIMessageTip.ShowError(user_name, "请设置正确的用户名！", 1000, true);
                return;
            }

            DataBaseStr.Remove(DataKeys.Uid);
            DataBaseStr.Add(DataKeys.Uid, user_name.Text);
            full_database_content.Text = GetFullDataStr(true);
        }

        private void password_Leave(object sender, EventArgs e)
        {
            if (password.Text == string.Empty)
            {
                UIMessageTip.ShowError(password, "请设置正确的用户名！", 1000, true);
                return;
            }

            DataBaseStr.Remove(DataKeys.Pwd);
            DataBaseStr.Add(DataKeys.Pwd, password.Text);
            full_database_content.Text = GetFullDataStr(true);
        }

        private void reset_contents_Click(object sender, EventArgs e)
        {
            ClearAndReset();
        }
    }
}